package com.lee.dianjiqi;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lee.dianjiqi.utils.MyNotice;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int FloatRequestCode = 1002;
    private static final int CODE_FOR_WRITE_PERMISSION = 0x10;

    private static final String TAG = "MainActivity";
    private EditText editTime;

    private boolean timeShow = false;
    private boolean clickShow = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏

        setContentView(R.layout.activity_main);
        TextView textPerm = findViewById(R.id.textPerm);
        TextView textPerm2 = findViewById(R.id.textPerm2);
        TextView textStart = findViewById(R.id.textStart);
        TextView textTime = findViewById(R.id.textTime);

        ImageView imageSub = findViewById(R.id.imageSub);
        ImageView imagePlus = findViewById(R.id.imagePlus);

        editTime = findViewById(R.id.editTime);
        textPerm.setOnClickListener(this);
        textPerm2.setOnClickListener(this);
        textStart.setOnClickListener(this);
        textTime.setOnClickListener(this);
        imageSub.setOnClickListener(this);
        imagePlus.setOnClickListener(this);
        reqPermissions();

        timeShow = false;
        clickShow = false;

    }


    private void reqPermissions() {

        boolean is = (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(getApplication(),
                Manifest.permission.READ_EXTERNAL_STORAGE) &&
                PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(getApplication(),
                        Manifest.permission.READ_PHONE_STATE));

        if (is) {

            Log.d(TAG, "有权限，直接");

        } else {

            Log.d(TAG, "开始授权");
            //没有权限，向用户请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            //Manifest.permission.CAMERA,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.INTERNET,
                            Manifest.permission.ACCESS_WIFI_STATE,
                            Manifest.permission.READ_PHONE_STATE,
                    }, CODE_FOR_WRITE_PERMISSION);

        }

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (!Settings.canDrawOverlays(this)) {
                Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
                startService(new Intent(MainActivity.this, FloatingClickService.class));
            }
        }
    }

    /***
     * 检查悬浮窗开启权限
     * @param context
     * @return
     */
    public boolean checkFloatPermission(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            return true;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                Class cls = Class.forName("android.content.Context");
                Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                declaredField.setAccessible(true);
                Object obj = declaredField.get(cls);
                if (!(obj instanceof String)) {
                    return false;
                }
                String str2 = (String) obj;
                obj = cls.getMethod("getSystemService", String.class).invoke(context, str2);
                cls = Class.forName("android.app.AppOpsManager");
                Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                declaredField2.setAccessible(true);
                Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName());
                return result == declaredField2.getInt(cls);
            } catch (Exception e) {
                return false;
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                if (appOpsMgr == null)
                    return false;
                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), context
                        .getPackageName());
//                return Settings.canDrawOverlays(context) || mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED;
                return Settings.canDrawOverlays(context) || mode == AppOpsManager.MODE_ALLOWED;
            } else {
                return Settings.canDrawOverlays(context);
            }
        }
    }

    /**
     * 悬浮窗开启权限
     *
     * @param context
     * @param requestCode
     */
    public void requestFloatPermission(Activity context, int requestCode) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivityForResult(intent, requestCode);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.textPerm://开启悬浮窗权限

                if (!checkFloatPermission(getApplicationContext())) {
                    Log.d(TAG, "未授权，开始授权");
                    requestFloatPermission(this, FloatRequestCode);
                } else {
                    Log.d(TAG, "已授权");
                    showToast("已授权");
                }

                break;

            case R.id.textPerm2://开启自动点击权限

                if (isAccessibilitySettingsOn(this, MyAccessibilityService.class))
                    showToast("已授权");
                else  //没有权限，去授权
                    startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));

                break;

            case R.id.textTime://开启时间弹窗
                clickTime();
                break;

            case R.id.textStart://开启电击器
                clickClick();
                break;

            case R.id.imagePlus://+1
                plusTime();
                break;

            case R.id.imageSub://-1
                subTime();
                break;

        }
    }

    private void subTime() {
        String s = editTime.getText().toString();
        try {
            int value = Integer.parseInt(s);
            if (value == 1)
                return;
            editTime.setText(String.valueOf(value - 1));
        } catch (Exception e) {
            e.printStackTrace();
            editTime.setText("5");
        }
    }


    private void plusTime() {
        String s = editTime.getText().toString();

        try {

            int value = Integer.parseInt(s);
            editTime.setText(String.valueOf(value + 1));
        } catch (Exception e) {
            e.printStackTrace();
            editTime.setText("5");
        }
    }


    private void clickClick() {


        if (!checkFloatPermission(getApplicationContext())) {
            showToast("请先授予弹窗权限");
            requestFloatPermission(this, FloatRequestCode);
            return;
        }

        if (isAccessibilitySettingsOn(this, MyAccessibilityService.class)) {
            startClick();
        } else { //没有权限，去授权
            showToast("没有权限，先授权");
            startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
        }
    }


    private void startClick() {
        String s = editTime.getText().toString();

        try {
            int i = Integer.parseInt(s);
            if (i < 0) {
                showToast("请设置大于0的时间间隔");
                return;
            }
            showClick(i);
        } catch (Exception e) {
            e.printStackTrace();
            showClick(5);
        }


    }

    private void showClick(int interval) {
        if (clickShow)
            return;

        Intent intent = new Intent(MainActivity.this, FloatingClickService.class);
        intent.putExtra("interval", interval);
        startService(intent);
        clickShow = true;

    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT);
    }

    private void clickTime() {

        if (timeShow)
            return;

        if (!checkFloatPermission(getApplicationContext())) {
            requestFloatPermission(this, FloatRequestCode);
        } else {
            Intent intent = new Intent(MainActivity.this, FloatingTimeService.class);
            startService(intent);
            timeShow = true;

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        //通过requestCode来识别是否同一个请求
        if (requestCode == CODE_FOR_WRITE_PERMISSION) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //用户同意，执行操作

            } else {
                Log.d(TAG, "用户不同意权限?????");
                Toast.makeText(getApplicationContext(), "未授权", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private boolean isAccessibilitySettingsOn(Context mContext, Class<? extends AccessibilityService> clazz) {
        int accessibilityEnabled = 0;
        final String service = mContext.getPackageName() + "/" + clazz.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyNotice.getInstance().clear();
    }

    public void add(View view) {

        try {
            TextView view1 = (TextView) view;
            String s = view1.getText().toString();
            int i = Integer.parseInt(s);
            view1.setText(++i + "");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}